package com.example.administrator.text;

import android.annotation.TargetApi;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.percent.PercentRelativeLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import app.BaseActivity;
import app.MyApplication;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import data.SharedPreferencesUtils;
import util.AgentIp;
import util.BReceiverUtil.SMSBroadcastReceiver;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.JumpActivityUtils;
import util.NetUtils;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import util.getInformation;
import view.diaLogView.PhoneMessageDialog;
import view.diaLogView.RetunDialog;
import view.diaLogView.UploadDialog;

/**
 * 再次登录提示页
 */
public class EntryPromptActivity extends BaseActivity {
    private String mToken,mid;
    private String mStringPhone;
    private String mStringPassword;         //注册或登录信息
    public boolean mJuderMessage = true;                                       //记录点击获取短信的次数
    private UploadDialog mUploadDialog;
    private RetunDialog mRetunDialog;
    private SMSBroadcastReceiver mSmsBroadcastReceiver;

    @Bind(R.id.linear_entrypromp)                LinearLayout mLinearLayout;
    @Bind(R.id.enterprompt_frame)                FrameLayout mFrameLayout;
    @Bind(R.id.PercentRelativeLayout_entryPrompt)PercentRelativeLayout mRelativeLayout;
    @Bind(R.id.edit_entryprompt_phone)           EditText mETEntryPhone;             //登录页，手机
    @Bind(R.id.edit_entry_buttom)                EditText mEditText;                //用于键盘弹起时的作用
    @Bind(R.id.edit_entryprompt_verification)    EditText mETTEntryPassword;       //登录页，密码或者手机验证码
    @Bind(R.id.text_entryprompt_oneland)         TextView mTVOneland;             //登录页，登录
    @Bind(R.id.text_entryprompt_verification)    TextView mTVerification;        //登录页，验证码
    @Bind(R.id.iamge_upload_entryprompt)         ImageView mIVUpload;           //登录页，Logo图标

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_entryprompt);
        ButterKnife.bind(this);
        init();
    }

    /**
     * 登录
     */
    @OnClick(R.id.text_entryprompt_oneland)
    void entryOneland() {
        if(NetUtils.getInstance(this).getNetWorkTeyt() == 0){
            mUploadDialog = new UploadDialog(this,"登录中");
            mUploadDialog.show();
            entry();
        }else {
            getJudgeIP();
        }

    }

    /**
     * 判断之前ip是否可用
     * type 0 一进来
     */
    public void getJudgeIP(){
        String id = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mUseridDB, "");
        mMap = new HashMap<>();
        if(id.equals("")){
            mMap.put("userid","0");
        }else {
            mMap.put("userid",id);
        }
        mMap.put("visitType",1);
        mMap.put("ip", getInformation.getNewGetInformation(this).getI_IP());
        mMap.put("mac",getInformation.getNewGetInformation(this).getIMAC());
        mMap.put("apMac",getInformation.getNewGetInformation(this).getWiFiMac());
        mMap.put("apName",getInformation.getNewGetInformation(this).getWIFIName());
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(mMap); //参数包
        mUploadDialog = new UploadDialog(this,"连接中");
        mUploadDialog.show();
        final long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngVersion_isAlive,stringJson,"null","0",time);
        final Map map = StringUtil.getStringUtilNew().getMapNew(this,stringJson,"null","0",Url.mStirngVersion_isAlive,stirngSign,time);
        String fwq = (String) SharedPreferencesUtils.getParam(this,HomeUtil.mFWQ,"");
        getLogger().info("getJudgeIP--->"+"fwq--"+fwq+"--type--"+"time"+StringUtil.getStringUtilNew().getTimeInstance()+"...NF_callid..."+map.get("NF_callid")+"..stringJson..."+stringJson);
        GreenTreeNetworkUtil.getInstance().doPost(this,fwq,2000,map,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("code") == 1) {
                        getLogger().info("getJudgeIP--->onSuccess--->"+"String--"+response);
                        if(jsonObject.getInt("siteAreaid") !=0){
                            entry();
                        }else {
                            //如果等于0 就再一次去找代理
                            seekSuccess();
                        }
                    }else {
                        seekSuccess();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    seekSuccess();
                }
            }

            @Override public void onFailure(Throwable error) {
                getLogger().info("getJudgeIP--->onFailure--->"+"time"+StringUtil.getStringUtilNew().getTimeInstance()+error);
                seekSuccess();
            }
        });
    }

    /**
     * 寻找代理
     */
    private void seekSuccess(){
        getLogger().info("seekSuccess()--->开始去找代理地址");
        AgentIp.newInstance(EntryPromptActivity.this).getIp(new AgentIp.OnAgentIpItemClickListener() {
            @Override
            public void onItemClick(String fwq) {
                getLogger().info("seekSuccess()--->onItemClick()代理地址"+fwq);
                if(fwq.equals("没有查到")){
                    mUploadDialog.dismiss();
                    failSuccess();
                }else {
                    if (!fwq.equals(Url.getUrlNew().getAppIP())) {
                        SharedPreferencesUtils.setParam(EntryPromptActivity.this, HomeUtil.mFWQ, fwq);
                    }
                    MyApplication.getApp().setFWQString(fwq);
                    entry();
                }
            }
        });
    }

    /**
     * 登录
     */
    private void entry(){
        if (NetUtils.getInstance(this).checkNetWork()) {
            if(getEntryObtain()){
                mToken = (String) SharedPreferencesUtils.getParam(EntryPromptActivity.this, HomeUtil.mTokenDB, "");
                mid= (String) SharedPreferencesUtils.getParam(this,HomeUtil.mUseridDB,"");
                HomeUtil.getHemeUtilNew().getEntry(this,mStringPhone,mStringPassword,mUploadDialog,null,HomeUtil.ENTRYPROMP);
            }else {
                mUploadDialog.dismiss();
            }
        } else {
            super.getToast(getString(R.string.no_network));
        }
    }

    /**
     * 代理失败后的操作
     */
    private void failSuccess(){
        if(mRetunDialog == null){
            if(!isFinishing()){
                if(mRetunDialog == null){
                    SharedPreferencesUtils.setParam(EntryPromptActivity.this, HomeUtil.mFWQ,"");
                    mRetunDialog = new RetunDialog(EntryPromptActivity.this,"wel",1,false);
                    mRetunDialog.show();
                }else {
                    mRetunDialog.show();
                }
            }
        }
    }


    /**
     * 获取验证码
     */
    @OnClick(R.id.text_entryprompt_verification)
    void verification() {

        if (StringUtil.getStringUtilNew().isMobile(mStringPhone)) {
            if (NetUtils.getInstance(this).checkNetWork()) {
                if (mJuderMessage) {
                    HomeUtil.getHemeUtilNew().getMessage(this,mETTEntryPassword,mSmsBroadcastReceiver);
                    mMap = new HashMap<>();
                    mMap.put("phone", mStringPhone);
                    mMap.put("authCodeType",0);

                    String stringJson = StringUtil.getStringUtilNew().hashMapToJson(mMap); //参数包
                    long time = StringUtil.getStringUtilNew().getTimeCurrent();
                    String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngPhoneVerification,stringJson,"null","0",time);
                    Map map1 = StringUtil.getStringUtilNew().getMapNew(this,stringJson,"null","0",Url.mStirngPhoneVerification,stirngSign,time);
                    HomeUtil.getHemeUtilNew().obtainVerification(this,map1,MyApplication.getApp().getFWQString(), mTVerification, 0,2);
                    mJuderMessage = false;
                } else {
                    PhoneMessageDialog phoneMessageDialog = new PhoneMessageDialog(this,mStringPhone,MyApplication.getApp().getFWQString(),mETTEntryPassword,mTVerification);
                    phoneMessageDialog.show();
                }

            } else {
                super.getToast(getString(R.string.no_network));
            }

        } else {
            super.getToast(getString(R.string.no_phone));
        }
    }

    /**
     * 忘记密码 免职声明
     */
    @OnClick(R.id.text_entryprompt_statement)
    void lookforStatement() {
        String url = "file:///android_asset/xieyi.html";
        JumpActivityUtils.getInstance().jumpWebView(this, url, getString(R.string.statement_web));
    }


    /**
     * 初始化
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void init() {
        HomeUtil.getHemeUtilNew().getStatusBar(this, mFrameLayout);

        String phone = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mHUWePhone, "");
        if (!phone.equals("")||!phone.equals("1")) {
            mETEntryPhone.setText(phone);
            mStringPhone = mETEntryPhone.getText().toString();
            if(mStringPhone.length() == 11){
                mTVerification.setTextColor(getResources().getColor(R.color.newfi_ba_true));
            }else {
                mTVerification.setTextColor(getResources().getColor(R.color.newfi_ba_false));
            }
            HomeUtil.getHemeUtilNew().getControlKeyboardLayout(mRelativeLayout, mETTEntryPassword);
        }
//        mETEntryPhone.setText("18300049065");
//        mETTEntryPassword.setText("123456");
        rsizeInputBox(mLinearLayout,mEditText);
        mETTEntryPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mStringPassword = s.toString();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mETEntryPhone.addTextChangedListener(new TextWatcher() {
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 11) {
                    mTVerification.setTextColor(getResources().getColor(R.color.newfi_ba_true));
                    mStringPhone = s.toString();
                } else if (s.length() <11) {
                    mStringPhone = s.toString();
                    mTVerification.setTextColor(getResources().getColor(R.color.newfi_ba_false));
                }
            }

            @Override public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 弹出键盘时布局向上移，消失恢复正常
     */
    private void rsizeInputBox(final View root, final View scrollToView) {

        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                root.scrollTo(0, 0);
                root.getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight = root.getRootView().getHeight() - rect.bottom;
                //若不可视区域高度大于100，则键盘显示
                if (rootInvisibleHeight > 100) {
                    int[] location = new int[2];
                    //获取scrollToView在窗体的坐标
                    scrollToView.getLocationInWindow(location);
                    //计算root滚动高度，使scrollToView在可见区域
                    int srollHeight = (location[1] + scrollToView.getHeight()) - rect.bottom;
                    root.scrollTo(0, srollHeight);
                } else {
                    //键盘隐藏
                    root.scrollTo(0, 0);
                }
            }
        });
    }

    /**
     * 获取和验证登录信息
     */
    private boolean getEntryObtain() {

        mStringPhone = mETEntryPhone.getText().toString().trim();
        mStringPassword = mETTEntryPassword.getText().toString().trim();

        if (!StringUtil.getStringUtilNew().isMobile(mStringPhone)) {
            super.getToast("手机号不正确");
            return false;
        }
        if (!StringUtil.getStringUtilNew().getStatePassword(mStringPassword)) {
            super.getToast("密码或验证码不正确");
            return false;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMap != null) {mMap.clear();}
        mJuderMessage = false;
        if(mSmsBroadcastReceiver !=null){
            unregisterReceiver(mSmsBroadcastReceiver);
        }
        if(mUploadDialog != null){
            mUploadDialog.dismiss();
        }
        if(mRetunDialog != null){
            mRetunDialog.dismiss();
        }
    }
}
